﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Configuration;

namespace WebAddressBook
{
    public partial class CreateContact : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitDDLEnterpirse();
                InitDDLDept();
            }
        }
        /// <summary>
        /// 初始化选择企业的下拉列表
        /// </summary>
        private void InitDDLEnterpirse()
        {
            //string strWhere = "len(DeptID)=4 and isDelete='false'";
            //Adrr.BLL.Base_Dept baseDeptBll = new Adrr.BLL.Base_Dept();
            //DataSet ds = baseDeptBll.GetList(strWhere);
            DataSet ds = CommonHelper.GetEnterprise();
            DDLEnterprise.DataSource = ds;
            DDLEnterprise.DataValueField = "DeptID";
            DDLEnterprise.DataTextField = "DeptName";
            DDLEnterprise.DataBind();
        }

        /// <summary>
        /// 初始化选择部门的下拉列表
        /// </summary>
        private void InitDDLDept()
        {
            string enterpriseId = DDLEnterprise.SelectedValue;
            //DataSet ds = CommonHelper.GetDept(enterpriseId);
            DataTable dt = CommonHelper.GetDeptList(enterpriseId);
            DDLDept.DataSource = dt;
            DDLDept.DataValueField = "DeptID";
            DDLDept.DataTextField = "DeptName";
            DDLDept.DataBind();
        }

        protected void BtCreate_Click(object sender, EventArgs e)
        {
            //如果还没创建企业或者部门，则不能创建联系人
            if (string.IsNullOrEmpty(DDLEnterprise.SelectedValue) || string.IsNullOrEmpty(DDLDept.SelectedValue))
            {
                LbMessage.Text = "<div class='box box-error'>添加失败！请先创建企业的组织架构！</div>";
                return;
            }

            if (!VerifyInpt())
            {
                LbMessage.Text = "<div class='box box-error'>带有 * 的字段不能为空！</div>";
                return;
            }

            Adrr.Model.Base_Employee baseEmployeeModel = new Adrr.Model.Base_Employee();

            //组织model  自定义Property还没做
            baseEmployeeModel.DeptID = DDLDept.SelectedValue;
            baseEmployeeModel.FstName = firstname.Value.Trim();
            baseEmployeeModel.SecName = lastname.Value.Trim();
            baseEmployeeModel.Sex = Convert.ToBoolean(RBsex.SelectedValue);
            baseEmployeeModel.Phone = phone.Value.Trim();
            baseEmployeeModel.Station = station.Value.Trim();
            baseEmployeeModel.Tel = tel.Value.Trim(); //tel.Value.Trim()== "" ? tel.Value.Trim() : null;
            baseEmployeeModel.FamiryTel = famirytel.Value.Trim();
            baseEmployeeModel.Email = email.Value.Trim();
            baseEmployeeModel.Fax = fax.Value.Trim();
            baseEmployeeModel.Address = address.Value.Trim();
            baseEmployeeModel.isDelete = false;
            baseEmployeeModel.CreateTime = DateTime.Now;
            baseEmployeeModel.UpdateTime = DateTime.Now;

            //如果有头像，就插入头像地址
            if (!string.IsNullOrEmpty(HFGuid.Value))
            {
                baseEmployeeModel.HeadUrl = imgCropped.ImageUrl;
                HFGuid.Value = "";
                //baseEmployeeModel.HeadUrl = "Heads/" + HFGuid.Value;
            }
            //baseEmployeeModel.HeadUrl = imgCropped.ImageUrl;

            //TODO
            //需要告诉手机端数据来源服务器位置
            //webconfig 配置
            //黄志明 2012-10-09
            baseEmployeeModel.FromServices = CommonHelper.DataServerUrl;

            //添加
            Adrr.BLL.Base_Employee baseEmployeeBll = new Adrr.BLL.Base_Employee();
            bool falg = baseEmployeeBll.Add(baseEmployeeModel);
            if (falg)
            {
                LbMessage.Text = "<div class='box box-info'>添加成功！</div>";
                ClearUI();
            }
            else
            {
                LbMessage.Text = "<div class='box box-error'>添加失败！</div>";
            }
        }
        /// <summary>
        /// 清空ui上显示的值
        /// </summary>
        private void ClearUI()
        {
            firstname.Value = "";
            lastname.Value = "";
            phone.Value = "";
            tel.Value = "";
            famirytel.Value = "";
            fax.Value = "";
            email.Value = "";
            station.Value = "";
            address.Value = "";
        }

        protected void DDLEnterprise_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitDDLDept();
        }

        private bool VerifyInpt()
        {
            if (string.IsNullOrEmpty(firstname.Value.Trim()) || string.IsNullOrEmpty(lastname.Value.Trim())
                || string.IsNullOrEmpty(phone.Value.Trim()))
                return false;
            else
                return true;
        }

        /*上传图片...上传的大图存放在ScrImage文件夹，裁剪后的托存放在Heads文件夹，
         * 为保证不发生图片的覆盖，上传和裁剪的图片全部采用guid做名字
         * */
        protected void BtUpload_Click(object sender, EventArgs e)
        {
            Boolean FileOK = false;
            Boolean FileSaved = false;

            if (Upload.HasFile)
            {
                String FileExtension = Path.GetExtension(Upload.FileName).ToLower();
                Session["WorkingImage"] = Guid.NewGuid().ToString() + FileExtension;//guid+图片的扩展名
                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (FileExtension == allowedExtensions[i])
                    {
                        FileOK = true;
                        break;
                    }
                }
            }

            if (FileOK)
            {
                try
                {
                    string path = HttpContext.Current.Request.PhysicalApplicationPath + "ScrImage\\";
                    Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                    FileSaved = true;
                }
                catch (Exception ex)
                {
                    LbMessage.Text = "<div class='box box-error'>图片上传不成功！</div>";
                    //lblError.Visible = true;
                    FileSaved = false;
                }
            }
            else
            {
                LbMessage.Text = "<div class='box box-error'>不能上传该类型的图片！</div>";
                //lblError.Visible = true;
            }

            if (FileSaved)
            {
                //pnlUpload.Visible = false;
                pnlCrop.Visible = true;

                //srcImgDiv.Visible = true;
                imgCrop.ImageUrl = "ScrImage/" + Session["WorkingImage"].ToString();
            }
        }
        //裁剪图片
        protected void btnCrop_Click(object sender, EventArgs e)
        {
            string ImageName = Session["WorkingImage"].ToString();

            int x, y, w, h;

            try
            {
                x = Convert.ToInt32(Math.Floor(Convert.ToDecimal(X.Value)));
                y = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Y.Value)));
                w = Convert.ToInt32(Math.Floor(Convert.ToDecimal(W.Value)));
                h = Convert.ToInt32(Math.Floor(Convert.ToDecimal(H.Value)));
            }
            catch (Exception ex)
            {
                LbMessage.Text = "<div class='box box-error'>请选择区域进行裁剪！</div>";
                return;
            }
            //上传的大图片的位置
            string scrImagePath = HttpContext.Current.Request.PhysicalApplicationPath + "ScrImage\\";
            byte[] CropImage = CommonHelper.Crop(scrImagePath + ImageName, w, h, x, y);
            using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
            {
                ms.Write(CropImage, 0, CropImage.Length);
                using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
                {
                    //裁剪后的地址
                    string headPath = HttpContext.Current.Request.PhysicalApplicationPath + "Heads\\";
                    //裁剪后图片的名字
                    HFGuid.Value = Guid.NewGuid().ToString() + "." + ImageName.Split('.')[1];

                    string SaveTo = headPath + HFGuid.Value;
                    CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                    pnlCrop.Visible = false;
                    //pnlCropped.Visible = true;
                    //srcImgDiv.Visible = false;

                    //imgCropped.ImageUrl = "Heads/" + HFGuid.Value;
                    
                    //数据库里面存的是这样格式的图片：http://host/Heads/uu.jpeg
                    imgCropped.ImageUrl =Request.Url.Scheme+"://"+Request.Url.Authority+"/Heads/" + HFGuid.Value;
                }
            }
        }

        #region comment
        //String path = HttpContext.Current.Request.PhysicalApplicationPath + "Heads\\";
        ////上传图片
        //protected void BtUpload_Click(object sender, EventArgs e)
        //{
        //    Boolean FileOK = false;
        //    Boolean FileSaved = false;

        //    if (Upload.HasFile)
        //    {
        //        Session["WorkingImage"] = Upload.FileName;
        //        String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
        //        String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
        //        for (int i = 0; i < allowedExtensions.Length; i++)
        //        {
        //            if (FileExtension == allowedExtensions[i])
        //            {
        //                FileOK = true;
        //                break;
        //            }
        //        }
        //    }

        //    if (FileOK)
        //    {
        //        try
        //        {
        //            Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
        //            FileSaved = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            LbMessage.Text = "<div class='box box-error'>图片上传不成功！</div>";
        //            FileSaved = false;
        //        }
        //    }
        //    else
        //    {
        //        LbMessage.Text = "<div class='box box-error'>不能上传该类型的图片！</div>";
        //    }

        //    if (FileSaved)
        //    {
        //        //pnlUpload.Visible = false;
        //        //pnlCrop.Visible = true;

        //        imgCrop.ImageUrl = "Heads/" + Session["WorkingImage"].ToString();
        //    }
        //}
        ////裁剪图片
        //protected void btnCrop_Click(object sender, EventArgs e)
        //{
        //    string ImageName = Session["WorkingImage"].ToString();
        //    int x = Convert.ToInt32(Math.Floor(Convert.ToDecimal(X.Value)));
        //    int y = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Y.Value)));
        //    int w = Convert.ToInt32(Math.Floor(Convert.ToDecimal(W.Value)));
        //    int h = Convert.ToInt32(Math.Floor(Convert.ToDecimal(H.Value)));

        //    byte[] CropImage =CommonHelper.Crop(path + ImageName, w, h, x, y);
        //    using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
        //    {
        //        ms.Write(CropImage, 0, CropImage.Length);
        //        using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
        //        {
        //            string SaveTo = path + "crop" + ImageName;
        //            CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
        //            //pnlCrop.Visible = false;
        //            //pnlCropped.Visible = true;
        //            imgCropped.ImageUrl = "Heads/crop" + ImageName;
        //        }
        //    }
        //}
        #endregion
    }
}